<template>
  <div>
    <el-upload
      drag
      :limit="limitNum"
      ref="upload"
      :auto-upload="false"
      accept=".xlsx"
      action="UploadUrl"
      :before-upload="beforeUploadFile"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :on-progress="uploadProcess"
      :on-success="handleSuccess"
      :on-error="handleError"
      :file-list="fileList"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div class="el-upload__tip" slot="tip">只能上传xlsx文件，且不超过10M</div>
    </el-upload>
    <br />
    <el-button size="small" type="primary" @click="uploadFile">立即上传</el-button>
    <el-button size="small">取消</el-button>
    <!-- <el-progress v-show="show" class="test" type="line" :percentage="UploadPercent"></el-progress> -->
  </div>
</template>

<script>
import XLSX from "xlsx";
export default {
  data() {
    return {
      limitNum: 1, // 上传excell时，同时允许上传的最大数
      fileList: [], // excel文件列表
      show: false,
      UploadPercent: 0
    };
  },
  methods: {
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$message.warning(
        `只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length +
          fileList.length} 个`
      );
    },
    // 文件状态改变时的钩子
    handleChange(file, fileList) {
      this.fileList.push(file.raw);
      this.show = true;
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      console.log("before upload");
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      if (extension !== "xlsx") {
        this.$message.warning("只能上传后缀是.xlsx的文件");
      }
      if (size > 10) {
        this.$message.warning("文件大小不得超过10M");
      }
    },
    // 指定删除的文件
    handleRemove(file, fileList) {
      this.fileList.splice(file, 1);
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.fileList = [];
      this.$message.success("文件上传成功");
    },
    //

    //上传进度
    uploadProcess(event, file, fileList) {
      this.UploadPercent = parseInt(file.percentage.toFixed(0));
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message.error("文件上传失败");
    },
    UploadUrl: function() {
      // 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
      return "";
    },
    uploadFile() {
      let that = this;
      // that.$refs.upload.submit();
      if (that.fileList.length === 0) {
        that.$message.warning("请上传文件");
      } else {
        that.fileList.forEach(element => {
          that.$commonFun
            .file2Xce(element)
            .then(res => {
              let batch_post_data = [];
              res.forEach(element => {
                element.sheet.forEach(el => {
                  let batch_post_json = {};
                  if (el["性别"] === "男") {
                    batch_post_json.gender = 0;
                  } else {
                    batch_post_json.gender = 1;
                  }
                  if (el["付款状态"] === "是") {
                    batch_post_json.payment_status = 1;
                  } else {
                    batch_post_json.payment_status = 0;
                  }
                  batch_post_json.school = that.$store.state.school_id;
                  batch_post_json.competition_season =
                    that.$store.state.seasonId;
                  batch_post_json.student_name = el["姓名"];
                  batch_post_json.birth_date = el["出生日期"];
                  batch_post_json.payment_amount = el["付款金额"];
                  batch_post_json.contact_name = el["联系人姓名"];
                  batch_post_json.contact_phone = el["联系人电话"];
                  batch_post_json.ID_number = el["身份证号"];
                  batch_post_data.push(batch_post_json);
                });
              });
              that.$api
                .batchAddStuInfo(batch_post_data)
                .then(res => {
                  that.handleSuccess();
                })
                .catch(err => {
                  that.$message({
                    type: "warning",
                    message: "文件上传失败！"
                  });
                });
            })
            .catch(err => {
              that.$message({
                type: "warning",
                message: "文件上传失败！"
              });
            });
        });
      }
    }
  }
};
</script>

<style scoped>
</style>

